import sys
import random
from PyQt5.QtWidgets import QApplication, QMainWindow, QMessageBox
from PyQt5.QtGui import QPainter, QColor
from PyQt5.QtCore import Qt, QTimer

class SnakeGame(QMainWindow):
    def __init__(self):
        super().__init__()
        self.init_game()
        self.setWindowTitle('贪吃蛇游戏')
        self.setGeometry(100, 100, 640, 480)
        self.show()

    def init_game(self):
        self.snake = [(100, 100), (90, 100), (80, 100)]
        self.direction = Qt.Key_Right
        self.food = self.place_food()
        self.timer = QTimer()
        self.timer.timeout.connect(self.update_game)
        self.timer.start(200)

    def place_food(self):
        x = random.randint(0, 63) * 10
        y = random.randint(0, 47) * 10
        while (x, y) in self.snake:
            x = random.randint(0, 63) * 10
            y = random.randint(0, 47) * 10
        return (x, y)

    def update_game(self):
        head_x, head_y = self.snake[0]
        if self.direction == Qt.Key_Up:
            head_y -= 10
        elif self.direction == Qt.Key_Down:
            head_y += 10
        elif self.direction == Qt.Key_Left:
            head_x -= 10
        elif self.direction == Qt.Key_Right:
            head_x += 10

        if (head_x, head_y) == self.food:
            self.snake.insert(0, (head_x, head_y))
            self.food = self.place_food()
        else:
            self.snake.insert(0, (head_x, head_y))
            self.snake.pop()

        if (head_x < 0 or head_x >= 640 or head_y < 0 or head_y >= 480 or
                (head_x, head_y) in self.snake[1:]):
            self.game_over()

        self.update()

    def game_over(self):
        self.timer.stop()
        QMessageBox.information(self, '游戏结束', '你输了！')
        self.init_game()

    def keyPressEvent(self, event):
        if event.key() in (Qt.Key_Up, Qt.Key_Down, Qt.Key_Left, Qt.Key_Right):
            if (event.key() == Qt.Key_Up and self.direction != Qt.Key_Down) or \
               (event.key() == Qt.Key_Down and self.direction != Qt.Key_Up) or \
               (event.key() == Qt.Key_Left and self.direction != Qt.Key_Right) or \
               (event.key() == Qt.Key_Right and self.direction != Qt.Key_Left):
                self.direction = event.key()

    def paintEvent(self, event):
        painter = QPainter(self)
        painter.setBrush(QColor(0, 150, 0))
        for segment in self.snake:
            painter.drawRect(segment[0], segment[1], 10, 10)

        painter.setBrush(QColor(255, 0, 0))
        painter.drawRect(self.food[0], self.food[1], 10, 10)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    game = SnakeGame()
    sys.exit(app.exec_())